const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const groupsCollection = db.collection('groups')

exports.main = async (event, context) => {
  const { planId, userInfo } = event
  const wxContext = cloud.getWXContext()
  
  try {
    // 获取分组计划
    const plan = await groupsCollection.doc(planId).get()
    if (!plan.data) {
      throw new Error('分组计划不存在')
    }

    // 检查是否已经加入
    if (plan.data.members.some(m => m.openId === wxContext.OPENID)) {
      return {
        success: false,
        error: '您已经加入该分组'
      }
    }

    // 检查人数是否已满
    if (plan.data.members.length >= plan.data.totalMembers) {
      return {
        success: false,
        error: '分组人数已满'
      }
    }

    // 将用户添加到成员列表
    const newMember = {
      openId: wxContext.OPENID,
      nickName: userInfo.nickName,
      avatarUrl: userInfo.avatarUrl,
      joinTime: new Date(),
      groupIndex: plan.data.groups.findIndex(group => 
        group.includes(plan.data.members.length)
      )
    }

    await groupsCollection.doc(planId).update({
      data: {
        members: db.command.push(newMember)
      }
    })

    return {
      success: true,
      data: newMember
    }
  } catch (err) {
    console.error(err)
    return {
      success: false,
      error: err.message
    }
  }
} 